package com.wxzz.elearning.common.aop;

import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.IPUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class IdempotentAspect implements Ordered {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.wxzz.elearning.common.aop.Idempotent)")
    public void currentLimitingCut() {
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Around("currentLimitingCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Idempotent annotation = method.getAnnotation(Idempotent.class);
        String ipAddr = "";
        try {
            //进行幂等
            if (annotation != null) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                ipAddr = IPUtils.getIpAddr(request);
                Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(RedisConstants.IDEMPOTENT + ipAddr + ":" + method.getName(), String.valueOf(method.getParameters()), 5, TimeUnit.SECONDS);
                if (!aBoolean){
                    throw new ServiceException("操作频繁");
                }
            }
            return point.proceed();
        } finally {
            if (redisTemplate.hasKey(RedisConstants.IDEMPOTENT + ipAddr + ":" + method.getName())){
                redisTemplate.delete(RedisConstants.IDEMPOTENT + ipAddr + ":" + method.getName());
            }
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
